package com.x.Part2_Comparator;

import com.x.Part1_Comparable.Phone;
import org.junit.Test;

import java.util.Arrays;
import java.util.Comparator;

/**
 * ClassName: ComparatorTest
 * Package: IntelliJ IDEA
 * Description:
 * Written by HanXu
 * Create 2024.03.28 21:39
 */
public class ComparatorTest {

    @Test
    public void test1(){
        Phone[] phones = new Phone[5];

        phones[0] = new Phone("HuaWei", 7999);
        phones[1] = new Phone("OPPO", 5999);
        phones[2] = new Phone("vivo", 6999);
        phones[3] = new Phone("Honor", 6299);
        phones[4] = new Phone("iPhone", 9999);


        //Comparator接口的匿名实现类的匿名对象
        //比Comparable接口更灵活，可以随时更改排序规则
         Arrays.sort(phones, new Comparator<Phone>() {
             @Override
             public int compare(Phone o1, Phone o2) {
                 if(o1 instanceof Phone && o2 instanceof Phone){
                     /**
                      * 手写
                      * if(o1.getPrice()> o2.getPrice())
                      *     return 1;
                      * else if(o1.getPrice() < o2.getPrice())
                      *     return -1;
                      * else
                      *     return 0;
                     */
                     //调用包装类
                     return Integer.compare(o1.getPrice(),o2.getPrice());
                 }else
                     throw new RuntimeException("类型不匹配");
             }
         });


        for(int i = 0; i < phones.length; i++){
            System.out.println(phones[i]);
        }

    }
}
